import { join, extname, basename } from "path";
import { v4 as uuidv4 } from 'uuid'
import { IinitialState } from ".";
// import chokidar from 'chokidar'

const fs = window.require('fs')
const remote = window.require('electron').remote;
const Store = window.require('electron-store')

//判断文件夹师是否存在如果不存在就创建一个
const mkdir = function (folderpath: string) {
    try {
        if (!fs.existsSync(folderpath)) {
            fs.mkdirSync(folderpath);
        }
        return folderpath
    } catch (e) { }
}
// 文件新建
const settingsStore = new Store()
export const savedFileLocation: string = settingsStore.get('savedFileLocation') || mkdir(join(remote.app.getPath('documents'), 'ApiDoc'))
console.log(savedFileLocation)
//查下文件下 所有包含JSON 和文件夹
export interface IreddirtoString {
    index: string,
    drop_down: Boolean,
    child: IreddirtoString[] | null | [],
    id: string,
    type: 'folder' | "file",
    title: string,
    path: string
}
export function reddirtoString(arr: string, ind = ''): IreddirtoString[] {
    const result: string[] = fs.readdirSync(arr);
    let res = result.filter(value => {
        if (extname(value) === '.json') {
            return value
        } else {
            if (value !== '.git') {
                const path = arr + "/" + value;
                const start = fs.statSync(path);
                if (start.isDirectory()) {
                    return value
                }
            }
        }
    })
    return res.map((value, index) => {
        const path = arr + "/" + value;
        const start = fs.statSync(path);
        const type = start.isDirectory() ? "folder" : "file";
        let child = null;
        let indx = ind === '' ? index + '' : ind + "_" + index
        if (type === "folder") {
            child = reddirtoString(path, indx)
        }
        return {
            index: indx,
            drop_down: false,
            id: uuidv4(),
            title: basename(value, extname(value)),
            path,
            type,
            child
        }

    })
}


const chokidar = window.require('chokidar')
//文件监听
let isreadyfs = false
const readyfs = () => {
    console.log("isreadyfs")
    if (isreadyfs) {
        reddirtoString(savedFileLocation)
    }
}
let watcher: any
export const chokidarFun = () => {
    watcher = chokidar.watch(savedFileLocation, { ignored: /[\/\\]\./, persistent: true })
    watcher.on('change', (path: string) => readyfs())
    watcher.on('unlink', (path: string) => readyfs())
    watcher.on('addDir', (path: string) => readyfs())
    watcher.on('unlinkDir', (path: string) => readyfs())
    watcher.on('error', (error: string) => console.log(`Watcher error: ${error}`))
    watcher.on('ready', () => {
        isreadyfs = true
    })
}
export const chokidarclose = () => {
    watcher.close()
    setTimeout(() => {
        chokidarFun()
    }, 10);
}

//根据index 更改某一个属性值
export const indexof = (index: string[], state: IreddirtoString[], num = 1): IreddirtoString => {
    let data = state[parseInt(index[0])]
    if (index.length <= num) {

        return data
    }
    index.shift()
    if (data.child !== null && data.child.length > 0) {
        return indexof(index, data.child, num)
    }
    return data
}

